/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.ban.data.exchange.runner.tokenBucket.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author zwlin
 */
public class PairList<K, V> implements Iterable<Pair<K, V>> {

    List<Pair<K, V>> list;

    public PairList() {
        this.list = new ArrayList<>();
    }

    public PairList(K key, V value) {
        this();
        list.add(new Pair<>(key, value));
    }

    public void add(K key, V value) {
        list.add(new Pair<>(key, value));
    }

    public void addAll(Collection<? extends Pair<K, V>> pairs) {
        list.addAll(pairs);
    }

    public void remove(int index) {
        list.remove(index);
    }

    public void remove(Pair<K, V> pair) {
        list.remove(pair);
    }

    public void removeAll(K key) {
        for (int i = list.size() - 1; i >= 0; --i) {
            if (Objects.equals(list.get(i), key)) {
                remove(i);
            }
        }
    }

    public boolean contains(Pair<K, V> pair) {
        return list.contains(pair);
    }

    public boolean contains(K key) {
        if (list.stream().anyMatch((pair) -> (Objects.equals(pair.getKey(), key)))) {
            return true;
        }
        return false;
    }

    public Pair<K, V> get(int index) {
        return list.get(index);
    }

    public int size() {
        return list.size();
    }

    @Override
    public Iterator<Pair<K, V>> iterator() {
        return list.iterator();
    }
}
